package cn.jbolt.core.enjoy.directive;

import cn.jbolt.core.enumutil.JBoltEnum;
import cn.jbolt.core.enumutil.JBoltEnumBean;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;

import java.io.IOException;
import java.util.List;

/**
 * 处理枚举转select options
 *
 * @ClassName: EnumToOptionsDirective
 * @author: JFinal学院-小木 QQ：909854136
 * @date: 2021年01月07日
 */
public class EnumToOptionsDirective extends Directive {

	private Expr valueExpr;
	private int paraNum;

	@Override
	public void setExprList(ExprList exprList) {
		this.paraNum = exprList.length();
		if (paraNum == 0) {
			throw new ParseException("Wrong number parameter of #enumToOptions directive, one parameters allowed at most",
					location);
		} else if (paraNum > 1) {
			throw new ParseException("Wrong number parameter of #enumToOptions directive, only need one parameter",
					location);
		}

		if (paraNum == 1) {
			this.valueExpr = exprList.getExpr(0);
		}

		if (this.valueExpr == null) {
			throw new ParseException("the first parameter of #enumToOptions directive cannot be null", location);
		}
	}
	/**
	 * 输出空字符
	 *
	 * @param env
	 * @param writer
	 */
	private void outputNothing(Env env, Writer writer) {
		try {
			writer.write("");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		Object enumNameObj = this.valueExpr.eval(scope);
		if (enumNameObj != null) {
			String enumName = enumNameObj.toString();
			try {
				Class enumClass = Class.forName(enumName);
				List<JBoltEnumBean> beans = JBoltEnum.getEnumOptionList(enumClass);
				int size = beans.size();
				if(size == 0){
					outputNothing(env,writer);
				}else{
					StringBuilder sb = new StringBuilder();
					int index = 0;
					for(JBoltEnumBean enumBean:beans){
						sb.append(enumBean.getText()).append(":").append(enumBean.getValue().toString());
						if(index<size-1){
							sb.append(",");
						}
						index++;
					}
					try {
						writer.write(sb.toString());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			} catch (ClassNotFoundException e) {
				throw new RuntimeException(e);
			}

		}else{
			outputNothing(env,writer);
		}
	}
}
